<template>
  <div>
    <el-main style="width: 100%" class="adllin">
      <el-form
        :model="form1"
        ref="form1"
        :inline="true"
        label-width="100px"
        style="width: 100%"
        :rules="rules"
      >
        <div style="display: flex">
          <div>
            <el-row>
              <el-col :span="24">
                <el-form-item label="表码" prop="ipaddr">
                  <span class="text-size">{{ mabiao }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!-- <el-col :span="20">
            <el-form-item label="委托单位" prop="ipaddr">
              <el-select v-model="selectedItem" placeholder="请选择" @change="changeenterpriseName">
                <el-option v-for="item in enterpriseNamearr" :key="item.id" :label="item.name" value-key="item.id"
                  :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="委托人" prop="name1">
                  {{ name1 }}
                  <!-- <el-select v-model="form1.name1" placeholder="请选择" @change="changeenterpriseName1">
                <el-option v-for="item in enterpriseNamearr1" :key="item.userId" :label="item.label"
                  value-key="item.userId" :value="item.userId"></el-option>
              </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item label="联系电话" prop="mobile">
                  <span>{{ mobile }}</span>
                  <!-- <el-input type="input" v-model="form1.mobile"></el-input> -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-col>
                <el-form-item label="工程名称" prop="engineeringName">
                  <el-select
                    v-model="form1.engineeringName"
                    placeholder="请选择"
                    @change="getprojectlist"
                    style="width: 200px"
                  >
                    <el-option
                      v-for="item in engineeringOptions"
                      :key="item.id"
                      :label="item.name"
                      value-key="item.id"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-form-item label="工程地点" prop="address">
                <el-input type="input" v-model="form1.address"></el-input>
              </el-form-item>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-form-item label="建设单位" prop="constructionUnit">
                <el-input
                  type="input"
                  v-model="form1.constructionUnit"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-form-item label="监理单位" prop="supervisionUnit">
                <el-input
                  type="input"
                  v-model="form1.supervisionUnit"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-form-item label="设计单位" prop="designUnit">
                <el-input type="input" v-model="form1.designUnit"></el-input>
              </el-form-item>
            </el-row>
          </div>
          <div>
            <el-row class="margin-bottom-10">
              <el-col :span="20">
                <el-form-item label="勘察单位" prop="surveyUnit">
                  <el-input type="input" v-model="form1.surveyUnit"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-col :span="20">
                <el-form-item label="施工单位" prop="construcUnit">
                  <el-input
                    type="input"
                    v-model="form1.construcUnit"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-form-item label="工程概况" prop="overview">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="form1.overview"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-col :span="24">
                <el-form-item label="业务类型" prop="businessType">
                  <el-select
                    v-model="form1.businessType"
                    placeholder="请选择"
                    @change="onywlx"
                  >
                    <el-option
                      key="shiwai"
                      label="现场检测"
                      value="shiwai"
                    ></el-option>
                    <el-option
                      key="shinei"
                      label="室内检测"
                      value="shinei"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row class="margin-bottom-10">
              <el-col :span="24">
                <el-form-item label="委托日期" prop="commissionDate">
                  <el-date-picker
                    v-model="form1.commissionDate"
                    type="date"
                    placeholder="选择日期"
                    style="width: 140px"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-form-item label="附表" prop="ipaddr">
                <span
                  style="cursor: pointer; color: #46a6ff"
                  @click="onUploadTable"
                  >上传附表 {{ form1.attachedNum }}
                </span>
                <!-- <fileUploadImage v-model="form1.zizhiFile" /> -->
              </el-form-item>
            </el-row>
          </div>
          <div>
            <el-row
              class="margin-bottom-10"
              v-if="form1.businessType === 'shiwai'"
            >
              <el-col :span="20">
                <el-form-item label="试验项目" prop="ipaddr">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handleAddExperiment"
                    style="margin-bottom: 10px"
                    >增加</el-button
                  >
                  <el-row class="margin-bottom-10">
                    <el-col :span="30">
                      <el-table
                        :data="experimentList"
                        style="width: 100%; margin-bottom: 10px"
                      >
                        <el-table-column
                          prop="testMethod"
                          label="试验项目"
                        ></el-table-column>
                        <el-table-column
                          prop="amount"
                          label="数量"
                        ></el-table-column>
                        <el-table-column
                          prop="unit"
                          label="单位"
                        ></el-table-column>
                        <el-table-column label="操作" width="100">
                          <template slot-scope="scope">
                            <el-button
                              size="mini"
                              type="danger"
                              @click="handleDeleteExperiment(scope.row.id)"
                              >删除</el-button
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="margin-bottom-10">
              <el-col :span="24">
                <el-form-item
                  label="委托检测内容"
                  prop="ipaddr"
                  style="margin-bottom: 10px"
                >
                  <el-input
                    type="textarea"
                    v-model="form1.detectionContent"
                    :rows="4"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              class="margin-bottom-10"
              v-if="!DetectionContentmsg.shuiyang"
            >
              <el-form-item label="检测依据" prop="ipaddr">
                <el-input
                  type="textarea"
                  v-model="form1.accordingContent"
                  :rows="4"
                ></el-input>
              </el-form-item>
            </el-row>
          </div>
        </div>
        <!-- <el-row class="margin-bottom-10">
          <el-col :span="24" v-if="DetectionContentmsg.ZJDY">
            <el-form-item label="低应变" prop="" label-width="60px">
              <el-checkbox-group
                v-model="shiwaicheckList"
                @change="onshiwaicheckList"
              >
                <el-checkbox
                  v-for="item in DetectionContentmsg.ZJDY"
                  :key="item.id"
                  :label="item"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="DetectionContentmsg.yanyang">
            <el-form-item
              label="岩样"
              prop="DetectionContentmsg"
              label-width="60px"
            >
              <el-checkbox-group v-model="checkList" @change="oncheckList">
                <el-checkbox
                  v-for="item in DetectionContentmsg.yanyang"
                  :key="item.id"
                  :label="item"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="DetectionContentmsg.tuyang">
            <el-form-item label="土样" label-width="60px">
              <el-checkbox-group
                v-model="tuyangcheckList"
                @change="ontuyangcheckList"
              >
                <el-checkbox
                  v-for="item in DetectionContentmsg.tuyang"
                  :key="item.id"
                  :label="item"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="DetectionContentmsg.tufushi">
            <el-form-item label="土腐蚀" label-width="60px">
              <el-checkbox-group
                v-model="tufushicheckList"
                @change="ontufushicheckList"
              >
                <el-checkbox
                  v-for="item in DetectionContentmsg.tufushi"
                  :key="item.id"
                  :label="item"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="DetectionContentmsg.shuiyang">
            <el-form-item label="水样" label-width="60px">
              <el-checkbox-group
                v-model="shuiyangcheckList"
                @change="onshuiyangcheckList"
              >
                <el-checkbox
                  v-for="item in DetectionContentmsg.shuiyang"
                  :key="item.id"
                  :label="item"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row class="margin-bottom-10">
          <el-col style="text-align: center">
            <el-button @click="cancel1">取消</el-button>
            <el-button
              @click="onZaicunSubmit"
              type="primary"
              v-show="form1.showStatus != 3"
              >暂存</el-button
            >
            <el-button @click="onSubmit" type="primary">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- 上传附表 -->
      <el-dialog
        :close-on-click-modal="false"
        :title="title1"
        :visible.sync="opentableListdialog"
        width="500px"
        append-to-body
        @close="handleDialogClose"
      >
        <el-row class="margin-bottom-10">
          <el-col :span="20" class="mb10" style="display: flex">
            <span class="text-size">工程名称:</span>
            <span class="text-size" style="padding-left: 10px">{{
              uploadform.engineeringName
            }}</span>
          </el-col>

          <el-col :span="20">
            <span class="text-size">委托单编号:</span>
            <span class="text-size">{{ uploadform.number }}</span>
          </el-col>
        </el-row>
        <el-row
          class="margin-bottom-10 mt20"
          v-for="(item, index) in list"
          :key="item.id"
        >
          <el-col :span="5" class="text-size">附表({{ index + 1 }}):</el-col>
          <el-col :span="5">
            <span class="text-size" style="color: #1176ff">{{
              item.name
            }}</span>
          </el-col>
          <el-col :span="5">
            <!-- <span class="detailbtn mr20" @click="onDetail(item.id)">详情</span> -->
            <span class="detailbtn" @click="delTable(item.id)">删除</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col style="text-align: center; margin: 15px 0" :span="15">
            <el-button type="primary" @click="uploadBtnlist"
              >上传清单</el-button
            >
            <el-button @click="opentableListdialog = false">关闭</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <el-dialog
        :close-on-click-modal="false"
        :title="title"
        :visible.sync="openTableDialog"
        width="500px"
        append-to-body
      >
        <el-form :inline="true" :model="uploadform" ref="uploadform">
          <el-row class="margin-bottom-10">
            <el-col :span="20" class="mb10">
              <span class="text-size">工程名称:</span>
              <span class="text-size">{{ uploadform.engineeringName }}</span>
            </el-col>
            <el-col :span="20">
              <span class="text-size">委托单编号:</span>
              <span class="text-size">{{ uploadform.number }}</span>
            </el-col>
          </el-row>

          <!-- <el-row class="margin-bottom-10">
          <el-col :span="24">

            <el-form-item label="文件名称" style="margin-bottom: 10px;">
              <el-input type="input" v-model="uploadform.name" style=""></el-input>
            </el-form-item>

          </el-col>
        </el-row> -->
          <el-row class="margin-bottom-10">
            <el-col :span="24">
              <!-- <el-form-item label="" style="margin-bottom: 10px;">
              <el-input type="input" v-model="uploadform.fileUrl" style="width: 230px;"></el-input>
            </el-form-item> -->
              <div v-if="!businessType">
                <el-form-item label="业务类型" prop="ipaddr">
                  <el-select
                    v-model="uploadform.businessType"
                    placeholder="请选择"
                    @change="onchangeJC"
                  >
                    <el-option
                      key="shiwai"
                      label="室外检测"
                      value="shiwai"
                    ></el-option>
                    <el-option
                      key="shinei"
                      label="室内检测"
                      value="shinei"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <!-- <div > -->
              <el-upload
                class="upload-demo"
                v-if="businessType == 'shinei'"
                :limit="1"
                accept=".xlsx, .xls"
                :action="uploadImgUrl"
                :headers="headers"
                multiple
                :file-list="fileList"
                :on-success="handleSuccess"
                drag
                style="display: inline-block"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div class="el-upload__tip text-center" slot="tip">
                  <div class="el-upload__tip" slot="tip">
                    <a
                      :href="file1Url"
                      download="室内表格.xlsx"
                      style="list-style: none; color: #1176ff"
                      >附表模版下载</a
                    >
                    <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                  
                    @click="downloadFile1('室内表格.xlsx')">附表模版下载111</el-link> -->
                  </div>
                </div>
              </el-upload>
              <!-- </div> -->
              <div v-if="businessType == 'shiwai'">
                <!-- <div class="margin-bottom-10">
                  <span>请先选择模版</span>
                  <el-radio-group v-model="uploadform.type" style="margin-left: 10px;" @change="downloadfile">
                    <el-radio label="1">下载模板1</el-radio>
                    <el-radio label="2">下载模板2</el-radio>
                  </el-radio-group>
                </div> -->

                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :data="{ type: 1, commissionId: rowArr.id }"
                  :limit="1"
                  accept=".xlsx, .xls"
                  :headers="headers"
                  :action="uploadImgUrl2"
                  :on-success="handleFileSuccess"
                  drag
                  :file-list="fileList"
                >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                  <div class="el-upload__tip text-center" slot="tip">
                    <div class="el-upload__tip" slot="tip"></div>
                    <span>仅允许导入xls、xlsx格式文件。</span>
                  </div>
                </el-upload>
              </div>
            </el-col>
          </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onSubmit2">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="增加试验项目"
        :visible.sync="experimentDialogVisible"
        width="400px"
        :close-on-click-modal="false"
        append-to-body
      >
        <el-form
          :model="experimentForm"
          :rules="experimentRules"
          ref="experimentForm"
          label-width="100px"
        >
          <el-form-item label="试验项目" prop="testMethod">
            <el-select
              v-model="experimentForm.testMethod"
              @change="handleAttachedDataChange($event)"
              placeholder="请选择试验项目"
              filterable
            >
              <el-option
                v-for="item in experimentItemOptions"
                :key="item.dictLabel"
                :label="item.dictLabel"
                :value="item.dictLabel"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="amount">
            <el-input
              v-model="experimentForm.amount"
              placeholder="请输入数量"
              type="number"
              min="1"
            />
          </el-form-item>

          <el-form-item label="单位" prop="unit">
            <el-input v-model="experimentForm.unit" placeholder="请输入单位" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmAddExperiment"
            >确定</el-button
          >
          <el-button @click="experimentDialogVisible = false">取消</el-button>
        </div>
      </el-dialog>
    </el-main>
  </div>
</template>

<script>
import file1Url from "@/assets/download/室内表格.xlsx";

import { getToken } from "@/utils/auth";
import {
  uploadTable,
  addEnterprise,
  searchProject,
  ProjectSingleList,
  updateEnterprise1,
  exportEnterprise,
  listEnterpriseAll,
  geteditEnterprise,
  getSystemset,
  getAttachedList,
  delAttached,
  getDetectionContentChange,
  addAttachedData,
} from "@/api/enterprise/enterprise";
import {
  listAttachedDataAll,
  logicDelAttachedData,
} from "@/api/attachedData/attachedData";
import { listAllUser } from "@/api/system/user.js";
import { getProject } from "@/api/project/project";
import { getCommission, getEngineeringInfo } from "@/api/commission/commission";
import { debounce } from "@/utils";
import Cookies from "js-cookie";
import dayjs from "dayjs";

export default {
  props: {
    rowId: {
      type: [String, Number],
      default: null,
    },
    detectionOptions: {
      type: [Array],
      default: null,
    },
  },

  computed: {},
  data() {
    return {
      experimentList: [],
      experimentDialogVisible: false,
      experimentForm: {
        item: "",
        count: "",
      },
      experimentRules: {
        item: [
          { required: true, message: "请选择试验项目", trigger: "change" },
        ],
        count: [{ required: true, message: "请输入数量", trigger: "blur" }],
      },
      experimentItemOptions: [],
      rowArr: {},
      isdowntrue: true,
      file1Url,
      DetectionContentmsg: {},
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      uploadImgUrl2:
        process.env.VUE_APP_BASE_API + "/attached/attached/importData", //室外检测上传
      uploadImgUrl:
        process.env.VUE_APP_BASE_API + "/attached/attached/importDataNie", // //室内检测上传
      title: "",
      title1: "",
      uploadform: {},
      openTableDialog: false,
      opentableListdialog: false,
      selectedItem: null,
      selectedItem1: null,
      filetype: "",
      projectObj: {},
      enterpriseNamearr1: [],
      enterpriseNamearr: [],
      mabiao: "",
      name1: "",
      mobile: "",
      name1: "",
      userId: "",
      seluserId: "",
      list: [],
      shineiVal: "",

      form1: {
        selectedItem1: null,
        name1: "",
        constructionUnit: "",
        enterpriseId: "",
        engineeringId: "",
        enterpriseName: "",
        engineeringName: "",
        surveyUnit: "",
        overview: "",
        construcUnit: "",
        construcUnit: "",
        supervisionUnit: "",
        address: "",
        commissionDate: "",
        designUnit: "",
        accordingContent: "",
        detectionContent: "",
        enterpriseId: "",
        mobile: "",
        engineeringId: "",

        pdfFile: "",
        wordFile: "",
        businessType: "",
      },
      fileList: [],
      engineeringOptions: [],
      checkList: [],
      shuiyangcheckList: [],
      tuyangcheckList: [],
      tufushicheckList: [],
      arrayFormat: [],
      shiwaicheckList: [],
      businessType: "",
      checkedValues: {
        //选中的值
        checkList: [],
        tuyangList: [],
        shuiyangcheckList: [],
        tufushiList: [],
        shiwaicheckList: [], //室外低应变
      },
      rules: {
        name: [{ required: true, message: "请选择委托人", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入工程地点", trigger: "blur" },
        ],
        constructionUnit: [
          { required: true, message: "请输入建设单位", trigger: "blur" },
        ],
        supervisionUnit: [
          { required: true, message: "请输入监理单位", trigger: "blur" },
        ],
        designUnit: [
          { required: true, message: "请输入设计单位", trigger: "blur" },
        ],
        surveyUnit: [
          { required: true, message: "请输入勘察单位", trigger: "blur" },
        ],
        construcUnit: [
          { required: true, message: "请输入施工单位", trigger: "blur" },
        ],
        overview: [
          { required: true, message: "请输入工程概况", trigger: "blur" },
        ],
        businessType: [
          { required: true, message: "请选择业务类型", trigger: "change" },
        ],
        engineeringName: [
          { required: true, message: "请选择工程", trigger: "change" },
        ],
      },

      roleId: null,
      roles: [],
      enterpriseId: null,
      engineeringSearch: {},
    };
  },
  watch: {
    rowId: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.rowId = newVal;
          if (this.rowId) {
            geteditEnterprise(this.rowId).then((response) => {
              console.log("进入对对对");
              this.rowArr = response.data;
              this.getExperimentList();
              this.form1 = response.data;
              this.selectedItem = response.data.enterpriseName;
              this.form1.engineeringName = response.data.engineeringName;
              console.log(this.enterpriseNamearr1, "22222");
              const obj = this.enterpriseNamearr1.find((item) => {
                return item.userId === Number(response.data.name);
              });
              console.log(obj, "111", this.enterpriseNamearr1, "22222");
              this.form1.name1 = obj.userName;
            });
          } else {
            this.form1.engineeringName = "";
            this.form1.address = "";
            this.form1.constructionUnit = "";
            this.form1.supervisionUnit = "";
            this.form1.designUnit = "";
            this.form1.surveyUnit = "";
            this.form1.construcUnit = "";
            this.form1.overview = "";
            this.form1.businessType = "";
          }
        }
      },
      immediate: true,
    },
  },
  computed: {},
  created() {
    this.experimentList = [];
    //当前用户的信息
    let userInfo = JSON.parse(Cookies.get("userinfo"));
    this.roles = userInfo.roles;
    this.roleId = userInfo.roleId;
    this.enterpriseId = userInfo.enterpriseId;
    this.form1.name1 = userInfo.userName;
    this.form1.mobile = userInfo.phonenumber;
    this.mobile = userInfo.phonenumber;
    this.name1 = userInfo.userName;

    this.getDicts("detection_item_scene").then((res) => {
      this.experimentItemOptions = res.data;
    });

    this.getProject();
    this.getpeople(); //查询委托人
    this.getgclist(); // 查询企业信息
    this.getMabiao();
    console.log(this.rowArr.id);
    if (this.rowArr.id) this.getExperimentList();

    this.uploadform.engineeringName = this.rowArr.engineeringName;
    this.uploadform.number = this.rowArr.number;
  },
  methods: {
    handleAddExperiment() {
      this.experimentForm = { item: "", count: "" };
      this.experimentDialogVisible = true;
    },
    confirmAddExperiment() {
      // 判断是否上传附表
      if (!this.rowArr.id) {
        this.$message.error("请先上传附表");
        return;
      }
      this.$refs.experimentForm.validate((valid) => {
        if (valid) {
          this.rowId = this.rowArr.id;
          addAttachedData({
            ...this.experimentForm,
            status: 2,
            commissionId: this.rowArr.id,
            engineeringId: this.rowArr.engineeringId,
          })
            .then((res) => {
              this.getjcxm();
              this.msgSuccess("添加成功");
              this.getExperimentList(); // 重新获取试验项目列表
              this.experimentDialogVisible = false;
              this.experimentForm = { testMethod: "", amount: "" }; // 重置表单
            })
            .catch(() => {
              this.$message.error("添加失败");
            });
        }
      });
    },
    // 获取试验项目列表
    getExperimentList() {
      console.log(this.rowArr.id);
      if (this.rowArr.id) {
        listAttachedDataAll({ commissionId: this.rowArr.id }).then((res) => {
          this.experimentList = res.data;
        });
      }
    },
    // 删除试验项目
    handleDeleteExperiment(id) {
      this.$confirm("确认删除该试验项目?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          logicDelAttachedData(id).then((res) => {
            this.getjcxm();
            this.msgSuccess("删除成功");
            this.getExperimentList(); // 重新获取列表
          });
        })
        .catch(() => {});
    },
    oncheckList(val) {
      console.log(val, "111");
      this.checkedValues.checkList = val;
      this.updateAccordingContent();
    },
    onshuiyangcheckList(val) {
      this.checkedValues.shuiyangcheckList = val;
      this.updateAccordingContent();
    },
    ontuyangcheckList(val) {
      this.checkedValues.tuyangList = val;
      this.updateAccordingContent();
    },
    ontufushicheckList(val) {
      this.checkedValues.tufushiList = val;
      this.updateAccordingContent();
      // this.form1.accordingContent += val
    },
    onshiwaicheckList(val) {
      this.checkedValues.shiwaicheckList = val;
      this.updateAccordingContent();
    },
    updateAccordingContent() {
      const allValues = [
        ...(this.checkedValues.checkList || []),
        ...(this.checkedValues.shuiyangcheckList || []),
        ...(this.checkedValues.tuyangList || []),
        ...(this.checkedValues.tufushiList || []),
        ...(this.checkedValues.shiwaicheckList || []),
      ].filter(Boolean);

      this.form1.accordingContent = allValues.join(",");
    },
    onSubmit2() {
      this.uploadform.commissionId = this.rowArr.id;
      if (this.businessType == "shinei") {
        // this.uploadform.businessType = this.rowArr.businessType

        uploadTable(this.uploadform).then((res) => {
          this.$message.success(`上传成功`);
          this.openTableDialog = false;
          this.getfubiaoList();
          this.resetForm1();
          this.opentableListdialog = false;
          this.getjcxm(); //查询检测内容
        });
        return;
      }
      this.fileList = [];

      this.openTableDialog = false;
    },
    getjcxm() {
      let obj = {
        commissionId: this.rowArr.id,
        businessType: this.businessType,
      };
      getDetectionContentChange(obj).then((res) => {
        console.log(res.data, "res");
        // this.DetectionContentmsg = res.data.detection_content_str;
        // let str = "";
        // for (const key in res.data.detection_content) {
        //   res.data.detection_content[key].forEach((item) => {
        //     str += `/${item}`;
        //   });
        // }
        // console.log(str);
        // this.form1.accordingContent = str;
        // // this.updateAccordingContent()
        // const originalData = res.data.jiance;
        // const arrayFormat = Object.values(originalData)
        //   .map((item) => {
        //     const objStr = item.replace(/'/g, '"');
        //     const obj = JSON.parse(objStr);
        //     let project = this.detectionOptions[obj.project];
        //     return obj.hasOwnProperty("number") && obj.businessType == "shinei"
        //       ? `实验项目：${project}，数量：${obj.number}`
        //       : `实验项目：${obj.project}`;
        //   })
        //   .join("\n");
        // this.form1.detectionContent = arrayFormat;
        // console.log(this.form1.detectionContent, "112");

        this.form1.accordingContent = res.data.detection_content_str;
        this.form1.detectionContent = res.data.project_str;
      });
    },
    onchangeJC(val) {
      this.form1.category = val;
      this.shineiVal = val;
      if (val == "shinei") {
        this.nobusinessType = false;
        this.isbusinessType = true;
      }
      if (val == "shiwai") {
        this.nobusinessType = true;
        this.isbusinessType = false;
      }
    },
    //删除附表
    delTable(id) {
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delAttached(id);
        })
        .then(() => {
          this.getfubiaoList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //选中模版
    downloadfile(val) {
      console.log(val, "val");
      if (val == 1) {
        const link = document.createElement("a");
        link.download = "室外检测附表导入（模版1）.xlsx" || "download";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.isdowntrue = false;
      } else {
        const link = document.createElement("a");
        link.download = "室外检测附表导入（模版2）.xlsx" || "download";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.isdowntrue = false;
      }
    },
    //室外文件上传成功
    handleFileSuccess(res, file, fileList) {
      console.log(res, file);
      this.getfubiaoList();
      this.getjcxm(); //查询检测内容
      this.$message.success(`上传成功`);
    },
    handleSuccess(res) {
      console.log(res);
      this.uploadform.name = res.data.fileInfo.originalFilename;
      this.uploadform.fileUrl = res.data.fileInfo.url;
      this.uploadform.soilSample = res.data.sampleList.tuyang_num;
      this.uploadform.waterSample = res.data.sampleList.shuiyang_num;
      this.uploadform.rockSample = res.data.sampleList.yanyang_num;
      this.uploadform.soilCorrosion = res.data.sampleList.tufushi_num;
      // this.uploadform.name = res.data.fileInfo.originalFilename
      // this.uploadform.fileUrl = res.data.fileInfo.url
    },
    getfubiaoList(id) {
      let commissionId = this.rowArr.id;
      getAttachedList({ commissionId: id || commissionId }).then((res) => {
        this.list = res.rows;
        this.form1.attachedNum = res.rows.length;
      });
    },
    //选择业务类型
    onywlx(val) {
      if (val == "shiwai") {
        if (this.rowArr.id) {
          this.getExperimentList();
        } else {
          this.experimentList = [];
        }
      }
      this.businessType = val;
    },
    //上传附表
    onUploadTable() {
      let user = JSON.parse(Cookies.get("userinfo"));
      console.log("dgdgd");
      console.log(this.rowArr.id);
      // 判断id是否存在
      if (this.rowArr.id) {
        getCommission(this.rowArr.id)
          .then((res) => {
            this.uploadform = res.data;
            this.businessType = res.data.businessType;
            this.getfubiaoList(this.rowArr.id);
          })
          .catch(() => {
            this.$message.error("添加失败");
          });
        this.opentableListdialog = true;
        return;
      }

      this.form1.mobile = this.mobile;
      this.$refs["form1"].validate((valid) => {
        if (valid) {
          this.title1 = "上传附表";
          let obj = {
            ...this.form1,
            name: user.userId,
            tableCode: this.mabiao,
          };
          if (obj.commissionDate) {
            obj.commissionDate = dayjs(obj.commissionDate).format("YYYY-MM-DD");
          }
          addEnterprise(obj).then((res) => {
            this.sendNotice(res);
            this.opentableListdialog = true;
            this.uploadform = res.data;
            this.rowArr.id = res.data.id;
            this.form1 = res.data;
            this.form1.name1 = user.nickName;
            this.form1.name = user.userId;
            this.getfubiaoList(res.data.id);
          });
        }
      });
    },
    uploadBtnlist() {
      this.openTableDialog = true;
      this.title = "上传清单";
    },
    getMabiao() {
      getSystemset().then((res) => {
        this.mabiao = res.msg;
      });
    },
    //提交
    // onSubmit: debounce(function () {
    onSubmit() {
      this.$refs["form1"].validate((valid) => {
        if (valid) {
          let obj = {
            ...this.form1,
            name: this.seluserId,
            tableCode: this.mabiao,
            showStatus: 3,
          };
          obj.name = JSON.parse(Cookies.get("userinfo")).userId;
          // 判空
          if (!obj.detectionContent) {
            return this.$message.warning("请输入检测内容");
          } else if (!obj.accordingContent) {
            return this.$message.warning("请输入检测依据");
          } else if (!obj.commissionDate) {
            return this.$message.warning("请输入委托日期");
          }
          obj.commissionDate = dayjs(obj.commissionDate).format("YYYY-MM-DD");
          // 将experimentList转成字符串，以逗号分隔
          if (obj.businessType == "shiwai") {
            const experimentListStr = this.experimentList
              .map((item) => item.id)
              .join(",");
            obj.adIds = experimentListStr;
          }
          if (this.rowArr.id || obj.id) {
            updateEnterprise1(obj).then((response) => {
              this.experimentList = [];
              this.msgSuccess("提交成功");
              this.$emit("closeOpenDialog");
              this.$emit("getList", "tj");
            });
            return;
          }
          addEnterprise(obj).then((res) => {
            this.experimentList = [];
            this.sendNotice(res);
            this.msgSuccess("提交成功");
            this.reset();
            this.$emit("getList", "tj");
            this.$emit("closeOpenDialog");
          });
          // if (this.rowId == null || this.rowId == "") {
          //   addEnterprise(obj).then((res) => {
          //     this.sendNotice(res);
          //     this.msgSuccess("提交成功");
          //     this.$emit("getList");
          //     this.$emit("closeOpenDialog");
          //     this.reset();
          //   });
          // } else {
          //   updateEnterprise1(obj).then((response) => {
          //     this.msgSuccess("提交成功");
          //     this.$emit("closeOpenDialog");
          //     this.$emit("getList", "zc");
          //   });
          // }
        }
      });
    },

    onZaicunSubmit() {
      this.form1.name1 = this.name1;
      this.form1.mobile = this.mobile;
      this.$refs["form1"].validate((valid) => {
        if (valid) {
          let obj = {
            ...this.form1,
            name: this.seluserId,
            tableCode: this.mabiao,
            showStatus: 2,
          };
          obj.name = JSON.parse(Cookies.get("userinfo")).userId;
          if (obj.commissionDate != "Invalid Date") {
            obj.commissionDate = dayjs(obj.commissionDate).format("YYYY-MM-DD");
          }
          if (obj.commissionDate == "Invalid Date") {
            obj.commissionDate = "";
          }
          console.log(obj, "obj");
          if (obj.businessType == "shiwai") {
            const experimentListStr = this.experimentList
              .map((item) => item.id)
              .join(",");
            obj.adIds = experimentListStr;
          }
          // 判断有没有附表id
          if (this.rowArr.id || obj.id) {
            updateEnterprise1(obj).then((response) => {
              this.msgSuccess("修改成功");
              this.$emit("closeOpenDialog");
              this.$emit("getList", "zc");
            });
            return;
          }
          addEnterprise(obj).then((res) => {
            this.sendNotice(res);
            this.msgSuccess("新增成功");
            this.$emit("getList", "zc");
            this.$emit("closeOpenDialog");
            this.reset();
          });
          // if (this.rowId == null || this.rowId === "") {
          //   addEnterprise(obj).then((res) => {
          //     this.sendNotice(res);
          //     this.msgSuccess("新增成功");
          //     this.$emit("getList");
          //     this.$emit("closeOpenDialog");
          //     this.reset();
          //   });
          // } else {
          //   updateEnterprise1(obj).then((response) => {
          //     this.msgSuccess("修改成功");
          //     this.$emit("closeOpenDialog");
          //     this.$emit("getList");
          //   });
          // }
        }
      });
    },

    // }, 500),
    sendNotice(data) {},

    selectUserId(data) {
      getProject(data).then((response) => {
        this.userId = response.data.projectManagerId;
      });
    },

    getpeople() {
      listAllUser({ roleId: 3 }).then((res) => {
        let data = res.data;
        data.forEach(function (item) {
          item.label = item.userName + "(" + item.nickName + ")";
        });

        this.enterpriseNamearr1 = data;
      });
    },
    cancel1() {
      this.$emit("closeOpenDialog");
    },

    cancel() {
      this.openTableDialog = false;
    },
    // 表单重置
    reset() {
      this.rowArr.id = "";
      this.selectedItem = "";
      this.selectedItem1 = "";
      this.name1 = "";
      this.DetectionContentmsg = {};
      this.checkedValues = {};
      this.checkList = [];
      (this.shuiyangcheckList = []),
        (this.tuyangcheckList = []),
        (this.tufushicheckList = []),
        // this.mabiao = '',
        (this.seluserId = ""),
        (this.form1 = {
          id: "",
          selectedItem1: "",
          enterpriseId: "",
          engineeringId: "",
          number: "",
          engineeringName: "",
          commissionDate: "",
          accordingContent: "",
          detectionContent: "",
          engineeringName: "",
          mobile: "",
          enterpriseName: "",
          name1: "",
          pdfFile: "",
          wordFile: "",
          constructionUnit: "",
        });
      this.resetForm("form1");
    },
    changeenterpriseName1(val) {
      console.log(val, "val111");
      // this.form1.name1 = val.nickName;
      this.seluserId = val;
    },
    changeenterpriseName(val) {
      console.log(val, "3333");
      this.form1.enterpriseId = val.id;
      this.form1.enterpriseName = val.name;
      //this.selectedItem = val.name;
    },

    //根据工程名称查询工程信息
    getprojectlist(val) {
      console.log(val, "444");
      let engineering = val.id;
      getEngineeringInfo(engineering).then((res) => {
        //console.log(res)
        if (res.code == 200 && res.msg != "没有数据") {
          this.form1.address = res.data.address;
          this.form1.constructionUnit = res.data.constructionUnit;
          this.form1.supervisionUnit = res.data.supervisionUnit;
          this.form1.designUnit = res.data.designUnit;
          this.form1.surveyUnit = res.data.surveyUnit;
          this.form1.construcUnit = res.data.construcUnit;
          this.form1.overview = res.data.overview;
        }
      });
      this.form1.engineeringId = val.id;
      this.form1.engineeringName = val.name;
      //this.form1.selectedItem1 = val.name;
      // ProjectSingleList(val.id).then(res => {
      //   this.projectObj = res.data
      //   // this.form1.address = this.projectObj.address
      //   // this.form1.constructionUnit = this.projectObj.constructionUnit
      //   // this.form1.supervisionUnit = this.projectObj.supervisionUnit
      //   // this.form1.designUnit = this.projectObj.designUnit
      //   // this.form1.construcUnit = this.projectObj.construcUnit
      //   // this.form1.overview = this.projectObj.overview
      //   // this.form1.surveyUnit = this.projectObj.surveyUnit
      // })
    },

    //工程信息查询所有
    getProject() {
      //console.log(this.roles)
      for (let i = 0; i < this.roles.length; i++) {
        //console.log()
        if (this.roles[i].roleId == 6) {
          this.engineeringSearch.enterpriseId = this.enterpriseId;
          break;
        }
      }
      searchProject(this.engineeringSearch).then((res) => {
        this.engineeringOptions = res.data;
      });
    },
    //企业信息查询所有
    getgclist() {
      listEnterpriseAll().then((res) => {
        this.enterpriseNamearr = res.data;
      });
    },
    //关闭附表弹窗
    handleDialogClose() {
      //console.log("fdsgsd")
      this.getjcxm(); //查询检测内容
    },

    //
    handleAttachedDataChange(val) {
      let experimentItemOptions = this.experimentItemOptions;
      let unit = "";
      experimentItemOptions.forEach(function (item) {
        if (val == item.dictLabel) {
          unit = item.cssClass;
        }
      });
      this.experimentForm.unit = unit;
      console.log(unit);
    },
  },
};
</script>

<style lang="scss" scoped>
.adllin {
  .el-select {
    width: 350px;
  }

  .el-textarea {
    width: 300px;
  }

  .el-input {
    width: 200px;
  }
}

.el-form-item {
  width: 100%;
}

// v-deep .el-form-item .el-form-item__content {
//   width: 100%;
// }
// v-deep .el-form-item .el-input {
//   width: 100%;
// }
// v-deep .el-form-item .el-select {
//   width: 400px
// }
// v-deep .el-form-item .el-textarea {
//   width: 400px;
// }
.text-size {
  font-size: 14px;
  color: #606266;
}

.margin-bottom-10 {
  margin-bottom: 10px;
}

.detailbtn {
  font-size: 14px;
  color: #2b84fb;
  cursor: pointer;
}
</style>
